<?php

namespace App\Http\Controllers\Admin\Api;

use App\Exceptions\LogicException;
use App\Http\Controllers\Controller;
use App\Models\Api\Apis;
use App\Models\Api\ApisHeader;
use App\Models\Module\ProductModule;
use App\Utils\QueryUtil;
use App\Utils\ResUtil;
use App\Models\Adminer\Admins;

class ApisHeaderController extends Controller
{

    public function list()
    {
        $request = request()->all();
        $query = ApisHeader::where(function($query) use($request) {
            QueryUtil::selectBuild($query, $request, [
                ['api_id', '='],
                ['key', 'like', 'key'],
                ['value', 'key', 'value'],
                ['created_adminer', 'like', 'created_adminer'],
                ['updated_adminer', 'like', 'updated_adminer'],
                ['id', '=']
            ]);
        });

        $total = $query->count();
        $models = QueryUtil::queryList($query);
        $list = [];
        foreach($models as $i => $v) {
            $list[$i] = $v?->label()?->toArray();
        }
        $hasMore = QueryUtil::hasMore(sizeof($list));
        return $this->ok(compact('list', 'total', 'hasMore'));
    }

    public function edit()
    {
        $data = request()->only([
            'id', 'api_id', 'key', 'value'
        ]);
        $rule = [
            'id' => '',
            'api_id' => 'required',
            'key' =>  'required',
            'value' => 'string|required',
        ];
        $validator = validatorService()->checkValidator($rule, $data, ApisHeader::$fillables);
        if ($validator['code'] != 200) {
            throw new LogicException($validator['data']);
        }

        if($data['id'] ?? '') {
            $ApisHeader = ApisHeader::find($data['id']);
            if(!$ApisHeader) {
                throw new LogicException(ResUtil::NOT_DATA);
            }
        } else {
            $ApisHeader = new ApisHeader;
            $ApisHeader->created_adminer = Admins::getInfoById($this->authAdmin()->id);
        }

        $api = Apis::find($data['api_id']);
        if(!$api) {
            throw new LogicException('产品子模块不存在');
        }

        $ApisHeader->fill([
            'api_id' => $api->id,
            'key' =>  $data['key'],
            'value' => $data['value'],
            'updated_adminer' => Admins::getInfoById($this->authAdmin()->id),
        ]);
        $ApisHeader->save();
        return $this->ok();
    }

    public function enable()
    {
        $data = request()->all();
        $rule = [
            'id' => 'integer|required',
        ];
        $validator = validatorService()->checkValidator($rule, $data, ApisHeader::$fillables);
        if ($validator['code'] != 200) {
            throw new LogicException($validator['data']);
        }
        $ApisHeader = ApisHeader::find($data['id']);
        if(!$ApisHeader) {
            throw new LogicException(ResUtil::NOT_DATA);
        }
        $ApisHeader->delete();


        return $this->ok();
    }


}
